package org.zebra.web.support;

import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Condition;
import org.springframework.context.annotation.ConditionContext;
import org.springframework.core.env.Environment;
import org.springframework.core.type.AnnotatedTypeMetadata;
import org.zebra.web.annotation.crypto.AlgorithmType;

/**
 * ApiDecryptRequestBodyAdvice 和 ApiEncryptResponseBodyAdviceChain 注册条件
 *
 * @author zhanghongbin
 */
@Slf4j
public class ApiCryptoCondition implements Condition {

    @Override
    public boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata) {
        Environment environment = context.getEnvironment();
        String algorithm =
                environment.getProperty("zebra.web.crypto.algorithm", "").trim();
        if (algorithm.isEmpty()) {
            return false;
        }
        AlgorithmType algorithmType;
        try {
            algorithmType = Enum.valueOf(AlgorithmType.class, algorithm.toUpperCase());
        } catch (Exception e) {
            log.error("zebra.web.crypto.algorithm 中没有 " + algorithm + " 此算法", e);
            return false;
        }
        if (algorithmType == AlgorithmType.AES) {
            String secretKey = environment.getProperty("zebra.web.crypto.secret-key", "");
            if (secretKey.trim().isEmpty()) return false;
        } else {
            String privateKey =
                    environment.getProperty("zebra.web.crypto.private-key", "").trim();
            String publicKey =
                    environment.getProperty("zebra.web.crypto.public-key", "").trim();
            if (publicKey.isEmpty() || privateKey.isEmpty()) return false;
        }
        return true;
    }
}
